package com.cql.web.controller.business;

import com.cql.common.config.FoodCircleConfig;
import com.cql.common.core.DO.PictureDO;
import com.cql.common.core.DO.UserDO;
import com.cql.common.core.DTO.PictureDTO;
import com.cql.common.core.base.AjaxResult;
import com.cql.common.core.base.BaseController;
import com.cql.common.utils.DateUtils;
import com.cql.common.utils.file.FileUploadUtils;
import com.cql.common.utils.file.MimeTypeUtils;
import com.cql.common.utils.uuid.IdUtils;
import com.cql.framework.config.ServerConfig;
import com.cql.framework.config.security.service.TokenService;
import com.cql.service.business.PictureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;

/**
 * @author cql
 */
@RestController
@RequestMapping("/file")
public class FileController extends BaseController {


    @Autowired
    private TokenService tokenService;

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private FoodCircleConfig foodCircleConfig;

    @Autowired
    private PictureService pictureService;


    /**
     * 图片上传接口：
     * 图片包含：moment，avatar，cover等等
     * <p>
     * （1）校验文件类型
     * （2）校验文件大小
     * （3）设置文件名
     * （4）上传文件
     * <p>
     * http://localhost:8080/api/profile/img/40ae79ee-1fe8-4a5d-8a26-376ca56d88e3.png
     * 映射到
     * food_circle_web/target/classes/static/imgs/2021/12/05/40ae79ee-1fe8-4a5d-8a26-376ca56d88e3.png
     *
     * @param file
     * @param request
     * @return
     */
    @PostMapping("/upload/img")
    public AjaxResult imgUpload(@RequestBody @RequestParam("file") MultipartFile file, HttpServletRequest request) {

        try {

            UserDO user = tokenService.getLoginUser(request).getUserDO();

            //1.校验文件大小和文件类型
            FileUploadUtils.assertAllowed(file, MimeTypeUtils.IMAGE_EXTENSION);

            //2.设置文件名：时间戳+UUID.后缀
            String fileName = DateUtils.dateTimeNow() + IdUtils.fastUUID() + "." + FileUploadUtils.getExtension(file);

            //3.上传文件的真实路径
            String realPath = ResourceUtils.getURL("classpath:").getPath() + "static/imgs";
            //真实路径
            File desc = FileUploadUtils.getAbsoluteFile(realPath, fileName);

            //4.上传文件
            file.transferTo(desc);

            //5.设置访问url
            String url = serverConfig.getUrl() + foodCircleConfig.getProfile() + fileName;

            //6.新增数据库
            PictureDO pictureDO = new PictureDO();
            pictureDO.setUserId(user.getUserId());
            pictureDO.setSrc(url);
            pictureDO.setAlt(user.getAccount());

            logger.info("url {}", url);
            PictureDTO picture = pictureService.insertPicture(pictureDO);

            return AjaxResult.success(picture);
        } catch (Exception e) {
            logger.error("图片上传出错{}", e.getMessage());
            return AjaxResult.error(e.getMessage());
        }
    }

}
